/**
 * @class
 * @description 左下角面板信息
 * @constructor
 */
import BaseContext from '../context';
export default class Menu extends BaseContext {
  constructor(app, options) {
    super(app, options);
    this.timer = null;
  }
  // 初始化操作
  init() {
    this.loadHtml();
    this.initEvent();
    this.initListener();
  }

  initListener() {
    this.listener({
      chapterIndexChange: this.chapterChange.bind(this),
      scrollChapter: this.menuHideControl.bind(this),
      clickContainer: this.menuShowControl.bind(this)
    })
  }
  initEvent() {
    this.util.addEventListener(this.$prevChapter, 'click', () => this.gotoChapter('prev'))
    this.util.addEventListener(this.$nextChapter, 'click', () => this.gotoChapter('next'))
  }
  gotoChapter(flag) {
    const { nextChapterId, prevChapterId } = this.currentChapter;
    let id;
    if (flag === 'next') {
      id = nextChapterId;
    } else {
      id = prevChapterId;
    }
    if (id) {
      location.href = `/ac/${this.comicInfo.comicId}/${id}.html`
    }
  }

  menuShowControl() {
    this.timer = setTimeout(() => {
      let headerH = this.$header.offsetHeight;
      let footerH = this.$footer.offsetHeight;
      if (this.$header.offsetTop < 0) {
        headerH = footerH = 0;
      }
      this.$header.style.top = -headerH + 'px';
      this.$footer.style.bottom = -footerH + 'px';
    }, 0);
  }
  menuHideControl() {
    this.timer && clearTimeout(this.timer);
    let headerH = this.$header.offsetHeight;
    let footerH = this.$footer.offsetHeight;
    this.$header.style.top = -headerH + 'px';
    this.$footer.style.bottom = -footerH + 'px';
  }
  chapterChange(index) {
    if (!this.$chapterProgress) return;
    const currentChapter = this.currentChapter;
    const len = currentChapter.chapterList.length;
    this.$chapterProgress.innerHTML = `${currentChapter.chapterNumName} ${index || 1}/${len}`;
  }
  selectorDOM() {
    this.$header = this.container.querySelector('#js_header');
    this.$footer = this.container.querySelector('#js_footer');
    this.$nextChapter = this.container.querySelector('#js_nextChapter');
    this.$prevChapter = this.container.querySelector('#js_prevChapter');
    this.$chapterProgress = this.container.querySelector('#js_chapterProgress');
  }

  // 页面渲染
  loadHtml() {
    const template = this.template;
    if (template.menu) {
      const strNodes = template.menu({
        ...this.comicInfo,
      });
      const nodes = this.util.createDocumentHtml(strNodes);
      this.container.append(nodes);
      this.selectorDOM();
    }
  }
}
